﻿<?php
// TODO: handle null attributes
// TODO: clean up
// TODO: program sometime when my mind is not ragged
// does has_many return DatabaseObjects or what?
// what about saving has_many'ed objects?
// belongs_to?
// others?
class DatabaseObject {
  function __construct($tablename,$primary_key='id',$params='') {
    $this->tablename = $tablename;
    $this->params = $params; // we'll need these for saving it (UPDATE)
    $this->primary_key = $primary_key; // for relationships, auto-incrementing
    $this->columns = $GLOBALS['db']->$tablename->columns;
    // get columns
    if(empty($params)) {
      // this object wasn't made w/ params - it doesn't exist in the db
      $this->in_db = false;
    } else {
      // this was made with params, it's supposed to be in the db
      $data = $GLOBALS['db']->select($tablename,$params);
      if(!$data) {
        $this->in_db = false;
      } else {
        $this->in_db = true;
        $this->fill($data[0]);
      }
    }
  }
  // move data in an associative array into the object itself
  function fill($array) {
    foreach($array as $column=>$value) {
      $this->$column = $value;
    }
  }
  // move the object into an associative array
  function toArray() {
    $data = array();
    foreach($this->columns as $column) {
      $data[$column] = $this->$column;
    }
    return $data;
  }
  // mmm object oriented goodness
  function save() {
    if(!$this->in_db) {
      // no record exists of this in the db
      $highkey = $GLOBALS['db']->selectOne($this->tablename,$this->primary_key,'',array('order by'=>$this->primary_key))+1;
      $data = $this->toArray();
      $data[$this->primary_key] = $highkey;
      $GLOBALS['db']->insert($this->tablename,$data);
    } else {
      // this was already in the db
      $GLOBALS['db']->update($this->tablename,$this->toArray(),$params);
    }
  }
  /** domain logic **/
  function has_many($tablename,$thatkey) { // guess key? singularize(tablename) + this->primary key
    $thisdata = $this->toArray();
    $items = $GLOBALS['db']->select($tablename,array($thatkey=>$thisdata[$this->primary_key]));
    $belongings = array();
    if($items) {
      foreach($items as $item) {
        $belonging = new DatabaseObject($tablename,$thatkey);
        $belonging->fill($item);
        $belonging->in_db = true; // now it knows it exists in the db, but it still can't update itself cuz it wasn't created w/ params...
        array_push($belongings,$belonging);
      }
    }
    $this->$tablename = $belongings;
  }
}
?>